﻿using BaseUtils.Helper;
using MyMes.Mes;
using NWMES;
using NWMES.HttpClientUtil;
using NWMES.Mes;
using NWMES.Model;
using Service.src.Model.Folw;
using Service.src.NW.Enum;
using Service.src.NW.Model;
using Service.src.NW.Model.Enum;
using Service.src.NW.Model.Folw;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Service.src.NW.Processor.Core
{
    public class MesProcessor : BaseProcessor
    {
        internal static void Run(NodeProcessor Node, NodeInputParam Input)
        {
            if (Node.NodeStatus == NodeStatusEnum.STATIC_EXECUTION)
            {
                return;
            }
            bool isMesConfig = true;
            if (Input == null || Input.NodeMes == null)
            {
                isMesConfig = false;
                SendNodeLoggerWarning(Node, "MES接口配置异常,原因：", RuntimeErrorCodeEnum.NODE_INPUT_PARAM_NULL);
            }
            string sfc = null;
            string inventory = null;
            if (isMesConfig)
            {
                foreach (NodeDataSource item in Input.NodeMes.DataSources)
                {
                    string v = GetNodeInputParamValue(Node, item);
                    if (item.TargetParamName == ParamNameEnum.SFC.ToString())
                    {
                        sfc = v;
                    }
                    if (item.ParamName == ParamNameEnum.inventory.ToString())
                    {
                        inventory = item.Value;
                    }
                }
            }
            string ApiSection = Node.id + "_" + Node.nodeType;

            if (Node?.NodeInputParam?.NodeMes?.MesConfigSection != null)
            {
                NodeDataSource Section = GetNodeInputParam(Node, Node.NodeInputParam.NodeMes.MesConfigSection);
                if (Section != null&& (Section.Value != ""&& Section.Value !=null))
                {
                    ApiSection = Node.id + "_" + Section.Value;
                    SendNodeLoggerInfo(Node, $"使用MESCFG.ini配置项：{ApiSection}");
                }
                else
                {
                    SendNodeLoggerWarning(Node, $"MES配置文件配置项可能存在异常，已使用MESCFG.ini下的{ApiSection}项");
                }
            }

            List<MachineIntegrationParamData> MesDataCollection = new List<MachineIntegrationParamData>();
            bool tempStatus = true;
            Input.NodeMes?.DataCollection?.nodeMesDataCollectionItems?.ForEach(Param =>
            {
                if (tempStatus)
                {

                    if (Param.ParamData.DataType == ExtendedParameterDataType.LIST)
                    {
                        NodeDataSource NDS = GetNodeInputParam(Node, Param);
                        List<dynamic> MESDATA = NDS?.Value;
                        if (MESDATA == null)
                        {
                            SendNodeLoggerWarning(Node, $"属性：{NDS.ParamName},的数据为空");
                        }
                        else
                        {
                            foreach (var Inner in MESDATA)
                            {
                                MachineIntegrationParamData Item = new MachineIntegrationParamData();
                                Item.Name = Inner.Name;
                                if (Inner.DataType is string dataTypeString)
                                {
                                    Item.DataType = ConvertHelper.ToEnum<ExtendedParameterDataType>(Inner.DataType);
                                }
                                else
                                {
                                    Item.DataType = (ExtendedParameterDataType)Inner.DataType;
                                }

                                Item.Value = Inner.Value;

                                MesDataCollection.Add(Item);
                            }
                        }
                    }
                    else
                    {
                        MachineIntegrationParamData Item = new MachineIntegrationParamData();
                        Item.Name = Param.ParamData.Name;
                        Item.DataType = Param.ParamData.DataType;
                        NodeDataSource v = GetNodeInputParam(Node, Param);
                        if (v?.Value != null)
                        {
                            Item.Value = v.Value + "";
                        }
                        MesDataCollection.Add(Item);
                    }
                }
            });

            MesResult Res = new MesResult();
            try
            {
                SendNodeLoggerInfo(Node, $"当前执行MES接口：{Node.nodeType}");
                switch (Node.nodeType)
                {
                    case NodeTypeEnum.MES_GetResourceSfcServiceService:
                        Res = MesGetResourceSfcServiceService.RequestMes(sfc, ApiSection);
                        break;
                    case NodeTypeEnum.MES_MiFindCustomAndSfcData:
                        Res = MiFindCustomAndSfcData.RequestMes(sfc, inventory, ApiSection);
                        break;
                    case NodeTypeEnum.MES_MachineIntegration:
                        Res = MachineIntegration.RequestMes(sfc, MesDataCollection, ApiSection);
                        break;
                    case NodeTypeEnum.MES_DataCollectForResourceFAIServiceService:
                        Res = DataCollectForResourceFAIService.RequestMes(sfc, MesDataCollection, ApiSection);
                        break;
                    case NodeTypeEnum.MES_MiGetCustomerBarcodeDataServiceService:
                        Res = MESGetCustomerBarcodeData.RequestMes(sfc, ApiSection);
                        break;
                    case NodeTypeEnum.MES_MiAssembleComponentsToSfc: // 总成装配
                        string ZCM = sfc; // 总成码
                        Res = MiAssembleComponentsToSfcs.RequestMes(ZCM, null, ApiSection);
                        break;
                    case NodeTypeEnum.MES_MiReleaseSfcWithActivity: // 释放总成,模组码
                        Res = MiReleaseSfcWithActivity.RequestMes(ApiSection);
                        break;
                    case NodeTypeEnum.MES_MiModuleAutoInSet: // 释放套号
                        Res = MesModuleAutoInSet.RequestMes(sfc, new string[] { }, ApiSection);
                        break;
                    case NodeTypeEnum.MES_miAssembleAndCollectDataForSfc: // 模组装配
                        List<MachineIntegrationParamData> MesDataInventory = new List<MachineIntegrationParamData>();
                        Input.NodeMes?.InventoryArray?.nodeMesDataCollectionItems?.ForEach(Inventory =>
                        {
                            MachineIntegrationParamData Item = new MachineIntegrationParamData();
                            dynamic v = GetNodeInputParamValue(Node, Inventory);
                            if (v != null)
                            {
                                Item.Value = v + "";
                            }
                            Item.qty = Inventory.ParamData.qty;
                            MesDataInventory.Add(Item);
                        });

                        Res = MesMiAssembleAndCollectDataForSfcService.RequestMes(sfc, MesDataInventory, MesDataCollection);
                        break;
                    case NodeTypeEnum.HttpClient:
                        Res = Post(ApiSection, MesDataCollection);
                        break;
                }
            }
            catch (Exception ex)
            {
                SendNodeLoggerError(Node, $"{Node.id}:MES请求失败：{ex.Message}，" + ex.StackTrace);
            }
            SetNodeOutParamValue<MesResult>(Node, Res);
            Node.NodeStatus = Res.Success ? NodeStatusEnum.SUCCESS : NodeStatusEnum.ERROR;
            Node.Logger = new NodeLogger(Res.ToJson());
            //JavaScriptEvent.Send(JavaScriptEventEnum.NODE_LOGGER, Node);
            string Message = Res.Message + "\r\n" + Res.Request;
            if (Res.Code == 0)
            {
                SendNodeLoggerInfo(Node, Message);
            }
            else
            {
                SendNodeLoggerError(Node, Message);
            }
            Complete(Node, Node.NodeStatus);
        }

        private static DXCode GetValueTemp()
        {
            DXCode obj = new DXCode();
            AppData.IPLCHelpers[0].ReadClass(obj, 3001, 2334);
            return obj;
        }

        public class DXCode
        {
            public CellResData[] List { get; set; } = new CellResData[50];
        }

        public class CellResData
        {
            public string f1 { get; set; }
            public int f2 { get; set; }
            public int f3 { get; set; }
        }

        public static MesResult Post(string ApiSection, List<MachineIntegrationParamData> MesData)
        {
            if (string.IsNullOrEmpty(ApiSection))
            {
                return new MesResult(-99, "接口参数配置异常");
                //networkCredential = new NetworkCredential(Params.UserName, Params.Password);
            }
            MESBaseService Param = MesBaseEntity.config[ApiSection].ToObject<MachineIntegration>();
            string ErrorMessage = Param.ParameterVerification();
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                return new MesResult(-99, ErrorMessage);
            }
            Param.InterfaceName = ApiSection;
            if (MesData != null || MesData.Count > 0)
            {
                Param.parametricDataArray = MesData;
            }
            Task<MesResult> Res = HttpRequest.Post(Param);

            return Res.Result;
        }
    }
}
